-module(model_user).
-compile(export_all).
-include_lib("stdlib/include/qlc.hrl").
-include("../db_structure.hrl").

%init() ->
%    mnesia:create_schema([node()]),
%    mnesia:start(),
%    mnesia:create_table(user,
%        [ {disc_copies, [node()] },
%             {attributes,      
%                record_info(fields,user)} ]).

insert(Username, Password) ->
    Fun = fun() ->
         mnesia:write(
         #user{ username=Username,password=chat_util:md5(Password)} 
         )
         end,
    case mnesia:transaction(Fun) of
     {aborted, Reason} ->
        ?ERROR_MSG("mnesia error: ~p.~n", [Reason]),
        {error, Reason};
     {atomic, Result} ->
        Result
    end.
  
select( Username) ->
    Fun = 
        fun() ->
            mnesia:read({user, Username})
        end,
    {atomic, [Row]}=mnesia:transaction(Fun),
    io:format(" ~p ~p ~n ", [Row#user.username, Row#user.password] ).

checkUserExist(Username) ->
    Fun = 
        fun() ->
            mnesia:read({user, Username})
        end,
   case mnesia:transaction( Fun ) of
     {aborted, Reason} ->
        ?ERROR_MSG("mnesia error: ~p.~n", [Reason]),
        {error, Reason};
     {atomic, Result} ->
        case length(Result) of
            0 -> 0;
            Length when Length > 0 -> 1
        end
   end.

getAll() ->
    Fun = fun() ->
            qlc:eval( qlc:q(
                [ X || X <- mnesia:table(user) ] 
            )) 
        end,
   case mnesia:transaction( Fun ) of
     {aborted, Reason} ->
        ?ERROR_MSG("mnesia error: ~p.~n", [Reason]),
        {error, Reason};
     {atomic, Result} ->
        Result
   end.
